﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ListContacts
{
    class Program
    {
        static void Main(string[] args)
        {
            String source = System.Environment.CurrentDirectory + @"\source.txt";
            String matchExpression = String.Empty;
            String output = String.Empty;
            List<String> contacts = new List<String>();

            int index = 0;

            AGAIN:
            String responce = String.Empty;

            try
            {
                Console.Write("Enter the starting index: ");
                index = int.Parse(Console.ReadLine().ToString());
                System.Console.Write("Enter the expression for match: ");
                matchExpression = Console.ReadLine().ToString();
                System.Console.Write("Enter the output file name: ");
                output = Console.ReadLine().ToString();
                output = output + ".txt";

                StreamReader reader = new StreamReader(source);
                String number = String.Empty;
                while ((number = reader.ReadLine()) != null)
                {
                    String matchup = number.Substring(index, matchExpression.Length);
                    if ( matchup == matchExpression)
                    {
                        contacts.Add(number);
                        Console.WriteLine(number);
                    }
                }
                reader.Close();

                if (!File.Exists(output))
                    File.Create(output).Close();

                File.WriteAllText(output, String.Empty);

                StreamWriter writer = new StreamWriter(output, true);
                
                foreach (String contact in contacts)
                {
                    writer.WriteLine(contact);
                }

                writer.Flush();
                writer.Close();                
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + "\n" + ex.Message + "\n" + ex.StackTrace);
            }

            Console.WriteLine("");
            Console.WriteLine("Total Contacts Found: " + contacts.Count);
            Console.ReadLine();
            
            
        }
    }
}
